<template>
  <div class="we-chat-content" :class="[systemSettingStore.$state.deskAppRangeType]">
    <nav>
      <div
        v-if="systemSettingStore.$state.deskAppRangeType === 'ios'"
        class="ios-tools"
        :class="{ blur: runningTaskStore.$state.currentTaskAppId !== appId }"
      >
        <span @click.stop="handleClose">
          <i class="iconfont wos-close fs10" />
        </span>
        <span @click.stop="handleMinimization">
          <i class="iconfont wos-minimization fs10" />
        </span>
        <span @click.stop="handleMaxMin">
          <i v-if="!isMax" class="iconfont wos-maximize fs10" />
          <i v-else class="iconfont wos-recover-window fs10" />
        </span>
      </div>
      <img src="../../../assets/images/weChat/avatar.jpg" alt="avatar" />
    </nav>
    <div class="chat-user-list">
      <div class="top">
        <div class="search" @mousedown.stop @dblclick.stop>
          <i class="iconfont wos-search" />
          <input placeholder="搜索" />
        </div>
        <div class="add" @mousedown.stop @dblclick.stop></div>
      </div>
      <ul class="chat-user" @mousedown.stop @dblclick.stop>
        <li
          v-for="item in chatList"
          :key="item.id"
          :class="{ active: currentUserId === item.id }"
          @click="handleCheckUser(item.id)"
        >
          <img :src="getImageUrl(`weChat/${item.avatar.trim()}`)" alt="avatar" />
          <div class="content">
            <div class="name">
              <span>{{ item.name }}</span>
              <em>{{ item.list[item.list.length - 1]?.userListDate }}</em>
            </div>
            <div class="chat-message">{{ item.list[item.list.length - 1].content }}</div>
          </div>
        </li>
      </ul>
    </div>
    <div class="chat">
      <div class="chat-title pl26" :class="{ 'no-user': !currentUserId }">
        {{ chatContent?.name }}
      </div>
      <div v-if="currentUserId" class="chat-content" @mousedown.stop @dblclick.stop>
        <ul class="chat-list" ref="chatListDom">
          <template v-for="item in chatContent?.list" :key="item.id">
            <li v-if="item.type === 'sender'" class="sender">
              <div class="message" v-html="item.content"></div>
              <div class="avatar">
                <img src="@/assets/images/weChat/avatar.jpg" alt="avatar" />
              </div>
            </li>
            <li v-else-if="item.type === 'date'" class="date">
              <div class="time">{{ item.content }}</div>
            </li>
            <li v-else-if="item.type === 'from'" class="from">
              <div class="avatar">
                <img src="@/assets/images/weChat/avatar.jpg" alt="avatar" />
              </div>
              <div class="message" v-html="item.content"></div>
            </li>
          </template>
        </ul>
        <div class="send-wrapper">
          <div class="send-tools">
            <span class="mr18"><i class="iconfont wos-expression" /></span>
            <span class="mr18"><i class="iconfont wos-folder" /></span>
            <span class="mr18"><i class="iconfont wos-screenshot" /></span>
            <span class="mr18"><i class="iconfont wos-message" /></span>
          </div>
          <div class="send-content">
            <textarea v-model="chatMessage" @keydown.enter.prevent="handleSend"></textarea>
          </div>
          <div v-if="systemSettingStore.$state.deskAppRangeType === 'win'" class="send" :class="{ error: sendError }">
            <div class="btn" @click="handleSend">发送(S)</div>
            <div class="send-error">不能发送空白信息</div>
          </div>
        </div>
      </div>
      <div v-else class="chat-no-content d-f-c">
        <i class="iconfont wos-we-chat fs86" />
      </div>
      <div v-if="systemSettingStore.$state.deskAppRangeType === 'win'" class="tools" @mousedown.stop @dblclick.stop>
        <span @click.stop="handleMinimization">
          <i class="iconfont wos-minimization fs10" />
        </span>
        <span @click.stop="handleMaxMin">
          <i v-if="!isMax" class="iconfont wos-maximize fs10" />
          <i v-else class="iconfont wos-recover-window fs10" />
        </span>
        <span @click.stop="handleClose">
          <i class="iconfont wos-close fs10" />
        </span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, inject, nextTick, ref } from 'vue'
import { dateFormat, getChatDisDate, getImageUrl, randomWord } from '@/utils/utils'
import { useWeChatDBStore } from '@/stores/systemApp/weChatDB'
import { useSystemSettingStore } from '@/stores/desk/systemSetting'
import { useRunningTasksStore } from '@/stores/taskBar/runningTasks'
import type { IChat, IChatDB } from '@/components/systemWindow/weChat/chatDB'

const weChatDBStore = useWeChatDBStore()
const systemSettingStore = useSystemSettingStore()
const runningTaskStore = useRunningTasksStore()

let sendErrorTimer: ReturnType<typeof setTimeout> | null
const isMax = inject<boolean>('isMax')
const appId = inject<string>('appId')
const childMinimization = inject<() => void>('childMinimization')
const childMaxMin = inject<() => void>('childMaxMin')
const childHiddenToTray = inject<() => void>('childHiddenToTray')
const chatListDom = ref<HTMLElement>()
const currentUserId = ref<string>('')
const chatMessage = ref<string>('')
const sendError = ref<boolean>(false)
const chatList = computed(() => {
  return weChatDBStore.$state.chatDB.map((item) => {
    return {
      ...item,
      list: item.list.map((child, childIndex) => {
        if (childIndex < item.list.length - 2) return child
        return {
          ...child,
          userListDate: getChatDisDate(child.date)
        }
      })
    }
  })
})
const chatContent = computed<IChatDB | null>(() => {
  const find = weChatDBStore.$state.chatDB.find((item: IChatDB) => item.id === currentUserId.value)
  if (!find) return null
  let list: IChat[] = []
  find.list.forEach((item: IChat, index: number) => {
    if (index >= 1) {
      const disDate = new Date(item.date).getTime() - new Date(find.list[index - 1].date).getTime()
      if (disDate > 1000 * 10) {
        list.push(pushDate(item.date))
        list.push(item)
      } else {
        list.push(item)
      }
    } else {
      list.push(pushDate(item.date))
      list.push(item)
    }
  })
  return {
    ...find,
    list
  }
})

const pushDate = (date: string): IChat => {
  const disDate = getChatDisDate(date)
  const format = dateFormat('hh:mm', date)
  return {
    id: randomWord(20, 'chat-'),
    type: 'date',
    content: `${disDate}${disDate !== format ? ' ' + format : ''}`,
    user: '',
    date: '',
    avatar: ''
  }
}
const handleMinimization = () => {
  childMinimization?.()
}
const handleMaxMin = () => {
  childMaxMin?.()
}
const handleClose = () => {
  childHiddenToTray?.()
}
const handleCheckUser = (id: string) => {
  currentUserId.value = id
  handleScrollChat()
}

// 滚动到聊天底部
const handleScrollChat = async () => {
  await nextTick()
  if (chatListDom.value) chatListDom.value?.scrollTo(0, chatListDom.value?.scrollHeight)
}

// 发送消息
const handleSend = () => {
  if (chatMessage.value.trim().length <= 0) {
    sendError.value = true
    sendErrorTimer && clearTimeout(sendErrorTimer)
    sendErrorTimer = setTimeout(() => {
      sendError.value = false
    }, 3000)
    return
  }
  weChatDBStore.sendChat(currentUserId.value, chatMessage.value)
  chatMessage.value = ''
  handleScrollChat()
}
</script>

<style scoped lang="scss">
.we-chat-content {
  width: 100%;
  height: 100%;
  display: flex;

  &.ios {
    nav {
      width: 60px;
      min-width: 60px;
      background-color: rgba(46, 46, 46, 0.7);
      backdrop-filter: blur(10px);
      position: relative;

      .ios-tools {
        position: absolute;
        left: 50%;
        top: 5px;
        display: flex;
        transform: translateX(-50%);
        align-items: center;
        gap: 6px;

        &.blur span {
          background-color: var(--ios-blur) !important;
        }

        > span {
          width: 12px !important;
          height: 12px !important;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 10px;
          color: #000;

          &:hover {
            i {
              display: inline-block;
            }

            &:last-of-type {
              color: #000;
              background-color: var(--ios-max);
            }
          }

          > i {
            display: none;
          }

          &:nth-of-type(1) {
            background-color: var(--ios-close);
          }

          &:nth-of-type(2) {
            background-color: var(--ios-min);
          }

          &:nth-of-type(3) {
            background-color: var(--ios-max);
          }
        }
      }
    }

    .send-content {
      min-height: 100px !important;
    }
  }

  nav {
    width: 56px;
    min-width: 56px;
    height: 100%;
    background-color: rgb(46, 46, 46);
    display: flex;
    flex-direction: column;
    align-items: center;

    img {
      margin-top: 36px;
      width: 35px;
      height: 35px;
      object-fit: contain;
      object-position: center center;
    }
  }

  .chat-user-list {
    width: 250px;
    min-width: 250px;
    height: 100%;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    background-color: rgb(230, 229, 229);
    border-right: 1px solid rgb(214, 214, 214);

    .top {
      box-sizing: border-box;
      padding: 26px 12px 0;
      height: 60px;
      min-height: 60px;
      background-color: rgb(247, 247, 247);
      display: flex;
      justify-content: space-between;
      align-items: self-start;
      font-size: 12px;
      border-bottom: 1px solid rgb(233, 233, 233);

      .search {
        width: 190px;
        height: 27px;
        border-radius: 4px;
        background-color: rgb(226, 226, 226);
        display: flex;
        align-items: center;

        .wos-search {
          margin-left: 5px;
          margin-right: 5px;
          display: inline-block;
          transform-origin: center center;
          transform: scale(0.65);
        }

        input {
          outline: none;
          background-color: transparent;
          height: 100%;
          border: none;

          &:focus {
            border: none;
          }
        }
      }

      .add {
        width: 27px;
        height: 27px;
        line-height: 27px;
        border-radius: 4px;
        background-color: rgb(226, 226, 226);
        text-align: center;
        position: relative;

        &::before,
        &::after {
          content: '';
          position: absolute;
          background-color: #000;
        }

        &::before {
          width: 13px;
          height: 1px;
          left: 7px;
          top: 13px;
        }

        &::after {
          width: 1px;
          height: 13px;
          left: 13px;
          top: 7px;
        }
      }
    }

    .chat-user {
      height: 100%;

      > li {
        box-sizing: border-box;
        padding: 14px 20px 14px 14px;
        display: flex;
        justify-content: flex-start;
        align-items: center;

        &:hover {
          background-color: rgb(217, 216, 216);
        }

        &.active {
          background-color: rgb(195, 196, 196);
        }

        > img {
          width: 42px;
          height: 42px;
          object-fit: contain;
          object-position: center center;
          margin-right: 10px;
        }

        .content {
          width: calc(250px - 28px - 42px - 10px);
          height: 42px;
          display: flex;
          flex-direction: column;
          justify-content: space-between;

          .name {
            width: calc(250px - 28px - 42px - 10px);
            display: flex;
            align-items: flex-start;
            justify-content: space-between;

            span {
              display: block;
              font-size: 14px;
              width: 100%;
              white-space: nowrap;
              text-overflow: ellipsis;
              overflow: hidden;
            }

            em {
              display: block;
              white-space: nowrap;
              color: rgb(153, 153, 153);
            }
          }

          .chat-message {
            font-size: 12px;
            color: rgb(153, 153, 153);
            display: inline-block;
            width: calc(250px - 28px - 42px - 10px);
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
          }
        }
      }
    }
  }

  .chat {
    width: 100%;
    display: flex;
    flex-direction: column;
    position: relative;
    background-color: rgb(245, 245, 245);

    .chat-title {
      box-sizing: border-box;
      height: 60px;
      min-height: 60px;
      line-height: 60px;
      font-size: 18px;
      border-bottom: 1px solid rgb(214, 214, 214);

      &.no-user {
        border: none;
      }
    }

    .chat-content {
      height: calc(100% - 60px);
      box-sizing: border-box;
      display: flex;
      flex-direction: column;

      ul {
        height: 100%;
        overflow-y: auto;
        padding: 7px 30px 15px;
        box-sizing: border-box;

        li {
          &.sender,
          &.from {
            display: flex;
            justify-content: flex-end;
            margin-bottom: 15px;

            .message {
              user-select: text;
              font-size: 14px;
              max-width: 50%;
              margin-right: 12px;
              background-color: rgb(149, 236, 105);
              padding: 8px 10px;
              line-height: 1.6;
              border-radius: 6px;
              position: relative;
              white-space: pre-wrap;

              &::after {
                content: '';
                position: absolute;
                right: -14px;
                top: 10px;
                border: 7px solid transparent;
                border-left-color: rgb(149, 236, 105);
              }
            }

            .avatar {
              width: 36px;
              height: 36px;
              border-radius: 6px;
              overflow: hidden;

              img {
                width: 100%;
                height: 100%;
                object-fit: contain;
              }
            }
          }

          &.from {
            justify-content: flex-start;

            .message {
              margin-right: unset;
              margin-left: 12px;
              background-color: #fff;

              &::after {
                right: unset;
                left: -14px;
                border: 7px solid transparent;
                border-right-color: #fff;
              }

              &:hover {
                background-color: rgb(235, 235, 235);

                &::after {
                  border-right-color: rgb(235, 235, 235);
                }
              }
            }
          }

          &.sender {
            .message {
              &:hover {
                background-color: rgb(137, 217, 97);

                &::after {
                  border-left-color: rgb(137, 217, 97);
                }
              }
            }
          }

          &.date {
            text-align: center;
            margin-bottom: 12px;

            .time {
              display: inline-flex;
              padding: 0 6px;
              height: 20px;
              justify-content: center;
              align-items: center;
              border-radius: 4px;
              color: #fff;
              background-color: rgb(218, 218, 218);
            }
          }
        }
      }

      .send-wrapper {
        border-top: 1px solid rgb(236, 236, 236);
        padding: 0 32px 0 24px;
        display: flex;
        flex-direction: column;

        .send-tools {
          padding: 12px 0;
          height: 18px;
          min-height: 18px;
        }

        .send-content {
          width: 100%;
          height: 100%;
          min-height: 40px;

          textarea {
            font-size: 13px;
            outline: none;
            width: 100%;
            height: 100%;
            background-color: transparent;
          }
        }

        .send {
          display: flex;
          justify-content: flex-end;
          line-height: 32px;
          padding: 12px 0;
          position: relative;

          &.error .send-error {
            display: flex;
          }

          .send-error {
            display: none;
            position: absolute;
            right: -10px;
            top: 0;
            transform: translateY(-100%);
            height: 32px;
            padding: 0 10px;
            justify-content: center;
            align-items: center;
            box-sizing: border-box;
            border-radius: 4px;
            border: 1px solid rgb(182, 182, 182);
            background-color: #fff;

            &::after {
              content: '';
              position: absolute;
              right: 20px;
              bottom: -16px;
              border: 8px solid transparent;
              border-top-color: #fff;
              filter: drop-shadow(0 1px 0 rgb(182, 182, 182));
            }
          }

          .btn {
            width: 100px;
            height: 32px;
            display: flex;
            font-size: 14px;
            justify-content: center;
            align-items: center;
            border-radius: 4px;
            color: rgb(6, 174, 86);
            background-color: rgb(233, 233, 233);
          }
        }
      }
    }

    .chat-no-content {
      width: 100%;
      height: 100%;
      color: rgb(235, 235, 235);
    }

    .tools {
      position: absolute;
      right: 0;
      top: 0;

      > span {
        display: inline-flex;
        justify-content: center;
        align-items: center;
        width: 35px;
        height: 26px;

        &:hover {
          background-color: rgb(226, 226, 226);

          &:last-of-type {
            color: #fff;
            background-color: rgb(251, 115, 115);
          }
        }
      }
    }
  }
}
</style>
